const Koa = require("koa");
const Router = require("@koa/router");
const cors = require("koa2-cors");
const { koaBody } = require("koa-body");
const app = new Koa();
const router = new Router();
const { exec } = require("child_process");
const skiLogRouter = require("./ski_log");
app.use(koaBody());

// 服务端支持跨域
app.use(
  cors({
    origin: "*", // 允许所有域名跨域
    credentials: true, // 允许跨域的时候带着 cookie
  })
);

// 自动部署
router.post("/webhook", async (ctx) => {
  ctx.body = { success: true, message: "部署已开始!" };
  setTimeout(() => {
    exec("/var/www/excel-koa/deploy.sh", (error, stdout, stderr) => {
      if (error) {
        console.error("❌ 部署失败:", error.message);
        console.error(stderr);
      } else {
        console.log("✅ 部署成功:\n", stdout);
      }
    });
  }, 1000);
});

// 注册路由
app.use(router.routes()).use(router.allowedMethods());
app.use(skiLogRouter.routes()).use(skiLogRouter.allowedMethods());
app.listen(9000, () => console.log(`🚀 http://localhost:9000`));
